﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using snat.proxy.items.exceptions;
using snat.proxy;

namespace snat.proxy.items {
    public class DBMessage : Item, IComparable {

        public int MessageID { get; private set; }
        public string IDonNetwork { get; private set; }
        public DBEntity Sender { get; private set; }
        public List<DBEntity> Recipients { get; private set;} 
        public bool Restricted { get; private set; }
        public string Data { get; private set; }
        public DateTime Timestamp { get; private set; }

        //todo make instantiate better for greedy stuff, complex queries for this one
        public DBMessage(DataRow _row, params DataSet[] _auxilliary) {
            this.MessageID = _row.Field<int>("MessageID");
                this.Sender = new DBEntity(_row.Field<int>("EntityID"), _row.Field<string>("EntityName"));

                this.IDonNetwork = _row.Field<string>("IDOnNetwork");
                this.Restricted = _row.Field<bool>("Restricted");
                this.Data = _row.Field<string>("Data");
                this.Timestamp = _row.Field<DateTime>("TimeStamp");

                if (_auxilliary.Length > 0) {
                    DataTable recipientsTable = _auxilliary[0].Tables["Table"];
                    IEnumerable<DataRow> recipientsEnumerator =
                    from recipient in recipientsTable.AsEnumerable()
                    where recipient.Field<int>("MessageID") == this.MessageID
                    select recipient;
                    List<DBEntity> recipientList = new List<DBEntity>();
                    foreach (DataRow d in recipientsEnumerator) {
                        recipientList.Add(new DBEntity(d));
                    }
                    this.Recipients = recipientList;
                }
                else {
                    //todo check the same result
                    this.Recipients = new ListProxy<DBEntity>(@"SELECT EntityID, EntityName
                                                          FROM MessageReceive NATURAL JOIN Entity
                                                          WHERE MessageReceive.MessageID = " + MessageID).ToList();
                }
        }

        public int CompareTo(object obj) {
            return Timestamp.CompareTo((obj as DBMessage).Timestamp);
        }

        public override string ToString() {
            return MessageID.ToString();
        }
    }
}
